package es.hekorusoft.udpcache.messages;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.zip.GZIPInputStream;

/*
 This file is part of UDPCache.

 UDPCache is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 UDPCache is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with UDPCache.  If not, see <http://www.gnu.org/licenses/>.
 */
final class StreamReader {

	private byte[] buf;
	int offset;

	public StreamReader(byte[] data) {
		this.buf = data;
	}

	public final int getByte() {
		return buf[offset++];
	}

	public final int getInt() {
		int valor = 0;
		valor = valor | (0xFF000000 & buf[offset++] << 24);
		valor = valor | (0x00FF0000 & buf[offset++] << 16);
		valor = valor | (0x0000FF00 & buf[offset++] << 8);
		valor = valor | (0x000000FF & buf[offset++]);

		return valor;
	}

	public final long getLong() {

		long l = ((((long) buf[offset + 7]) & 0xFF) + ((((long) buf[offset + 6]) & 0xFF) << 8) + ((((long) buf[offset + 5]) & 0xFF) << 16)
				+ ((((long) buf[offset + 4]) & 0xFF) << 24) + ((((long) buf[offset + 3]) & 0xFF) << 32) + ((((long) buf[offset + 2]) & 0xFF) << 40)
				+ ((((long) buf[offset + 1]) & 0xFF) << 48) + ((((long) buf[offset]) & 0xFF) << 56));

		offset += 8;

		return l;
	}

	public final String getString() {
		int size = getInt();
		String ret = new String(buf, offset, size);
		offset += size;
		return ret;
	}

	public final Object getObject() {
		int size = getInt();
		Object obj = null;
		ByteArrayInputStream bais = new ByteArrayInputStream(buf, offset, size);
		ObjectInputStream ois;
		try {
			if (buf[offset] == 31 && buf[offset + 1] == -117 && buf[offset + 2] == 8) {
				ois = new ObjectInputStream(new GZIPInputStream(bais));
			} else {
				ois = new ObjectInputStream(bais);
			}
			obj = ois.readObject();
			ois.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		offset += size;
		return obj;

	}

	public final byte[] getByteArray() {
		int size = getInt();
		byte[] obj = new byte[size];
		System.arraycopy(buf, offset, obj, 0, size);
		offset += size;
		return obj;

	}
}
